package megrez.mail.sender.web;

import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import megrez.mail.sender.domain.QueryService;
import megrez.mail.sender.domain.TemplateConfig;
import megrez.mail.sender.domain.TemplateConfigRepository;
import megrez.mail.sender.domain.TemplateContent;
import megrez.mail.sender.domain.TemplateContentRepository;
import megrez.mail.sender.web.vo.TemplateConfigVO;
import megrez.mail.sender.web.vo.TemplateContentVO;

/**
 * 模板查询接口
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@RestController
@RequestMapping("/v1/templates")
public class TemplateQueryResource {
    @Autowired
    private QueryService querySrc;
    @Autowired
    private TemplateContentRepository templateContentRep;
    @Autowired
    private TemplateConfigRepository templateConfigRep;

    @GetMapping("/config/{id}")
    public TemplateConfigVO getConfigById(@PathVariable String id) {
        return TemplateConfigVO.of(querySrc.findConfigById(id));
    }

    @GetMapping("/config/{id}/content")
    public TemplateContentVO getContent(@PathVariable String id, @RequestParam(name="locale") Locale locale) {
        TemplateConfig config = querySrc.findConfigById(id);
        List<TemplateContent> contents = templateContentRep.findByTemplateConfigAndLocale(config, locale);
        if (contents.isEmpty()) {
            return new TemplateContentVO("", locale, "");
        }

        return TemplateContentVO.of(contents.get(0));
    }

    @GetMapping()
    public Page<TemplateConfigVO> getLogPage(@RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "enabled", required = false) Boolean enabled, Pageable pageable) {

        ExampleMatcher matcher = ExampleMatcher
                .matchingAll()
                .withMatcher("code", GenericPropertyMatchers.contains().ignoreCase())
                .withMatcher("remark", GenericPropertyMatchers.contains());

        TemplateConfig example = new TemplateConfig(null, code, remark, enabled);
        Page<TemplateConfig> page = templateConfigRep.findAll(Example.of(example, matcher), pageable);
        return page.map(TemplateConfigVO::of);
    }

}
